package main

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"image/color"
	"time"
)

type snakePart3 struct {
	x, y float32
}

var (
	snakeParts3 []snakePart3
	game3       *fyne.Container
)

type moveType3 int

const (
	moveUp3 moveType3 = iota
	moveDown3
	moveLeft3
	moveRight3
)

var move3 = moveUp3

func main() {
	a := app.New()
	w := a.NewWindow("Snake")

	w.Resize(fyne.NewSize(400, 400))
	w.SetFixedSize(true)

	game3 = setupGame3()
	w.SetContent(game3)
	w.Canvas().SetOnTypedKey(keyTyped3)
	go runGame3()
	w.ShowAndRun()
}

func setupGame3() *fyne.Container {

	var segments []fyne.CanvasObject
	// 创建10个小方框
	for i := 0; i < 10; i++ {

		seg := snakePart3{9, float32(5 + i)}
		snakeParts3 = append(snakeParts3, seg)

		// 创建方框
		r := canvas.NewRectangle(&color.RGBA{G: 0x66, A: 0xff})
		// 指定方框大小
		r.Resize(fyne.NewSize(10, 10))
		// 将方框放到指定位置
		r.Move(fyne.NewPos(190, float32(50+i*10)))
		segments = append(segments, r)
	}

	return container.NewWithoutLayout(segments...)
}

func refreshGame3() {
	for i, seg := range snakeParts3 {
		rect := game3.Objects[i]
		rect.Move(fyne.NewPos(seg.x*10, seg.y*10))
	}
	game3.Refresh()
}

func runGame3() {
	for {
		time.Sleep(time.Millisecond * 250)
		for i := len(snakeParts3) - 1; i >= 1; i-- {
			snakeParts3[i] = snakeParts3[i-1]
		}
		//snakeParts3[0].y--

		switch move3 {
		case moveUp3:
			snakeParts3[0].y--
		case moveDown3:
			snakeParts3[0].y++
		case moveLeft3:
			snakeParts3[0].x--
		case moveRight3:
			snakeParts3[0].x++
		}
		refreshGame3()

	}
}

func keyTyped3(e *fyne.KeyEvent) {
	switch e.Name {
	case fyne.KeyUp:
		move3 = moveUp3
	case fyne.KeyDown:
		move3 = moveDown3
	case fyne.KeyLeft:
		move3 = moveLeft3
	case fyne.KeyRight:
		move3 = moveRight3
	}
}
